package org.itboys.fuzion.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.itboys.commons.utils.random.RandomUtils;
import org.itboys.fuzion.tools.ClientCustomSSL;
import org.itboys.weixin.entity.CompanyPayConfig;
import org.itboys.weixin.tools.HttpClientUtil;
import org.itboys.weixin.tools.SignUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.alibaba.fastjson.JSON;

import ch.qos.logback.core.joran.spi.XMLUtil;

/**
 * Created by weishikui on 2016-03-24.
 */
public class HttpsPost {

    
    /**
	 * 随机生成一个订单号
	 * @return
	 */
	public static String generanOrderNo() {
		return DateFormatUtils.format(new Date(), "yyMMddHHmmss") + RandomUtils.buildRandom(6);
	}
	

    /**
     * 测试方法.
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        /*// 密码
        String password = "1227639702";
        // 密钥库
        String keyStorePath = "C:\\asd";
        // 本地起的https服务
        String httpsUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
       
        WeixinShopConfig ws = new WeixinShopConfig();
        ws.setNonceStr(generanOrderNo());
        ws.setMchBillno(password + "201604201234567891");
        ws.setMchId("1227639702");
        ws.setWxappId("wxb9b6d8965a301513");
        ws.setSendName("迷人汇");
        ws.setOpenId("oT9BYt-VPDD7x41fYevOG_EoHXw0");
        ws.setTotalAmount(100);
        ws.setTotalNum(1);
        ws.setWishing("哇嘎嘎嘎");
        ws.setClientIp("115.192.115.16");
        ws.setActName("大乱斗");
        ws.setRemark("大乱斗测试发红包");
        ws.setKey("sunday1302niujunhui888sunday1302");
        
        String sign = SignUtil.signToMD5(ws.sort());
        ws.setSign(sign);
        
        // 发起请求
        ClientCustomSSL.post(keyStorePath, password, httpsUrl, ws.toXml());*/
    	
    	 // 密码
        String password = "1335861101";
        // 密钥库
        String keyStorePath = "C:\\apiclient_cert.p12";
        // 本地起的https服务
        String httpsUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        
        CompanyPayConfig cpc = new CompanyPayConfig();
        cpc.setMchAppId("wx1760933753c5549d");
        cpc.setMchId("1335861101");
        cpc.setNonceStr("2016050112345678901234"+RandomUtils.buildRandom(10));
        cpc.setPartnerTradeNo("2016050112345678901234"+RandomUtils.buildRandom(10));
        cpc.setOpenId("oCnQEwbgYDhsv3w04hKxdUntF96I");
        cpc.setAmount(100);
        cpc.setDesc("恭喜发财，红包送来");
        cpc.setSpbillCreateIp("112.10.40.21");
        cpc.setCheckName("NO_CHECK");
        cpc.setKey("weicangwangluo123456789weicangwa");
        
        System.out.println("排序："+cpc.sort());
        String sign = SignUtil.signToMD5(cpc.sort());
        System.out.println("签名："+sign);
        cpc.setSign(sign);
        
        System.out.println("请求XML："+cpc.getXml());
        // 发起请求
        String re = ClientCustomSSL.post(keyStorePath, password, httpsUrl, cpc.getXml());
        Map<String, Object> pp = HttpsPost.doXMLParse(re);
        System.out.println("=========" + pp.get("result_code"));
        System.out.println(JSON.toJSONString(pp));
    }
    
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		
		Map m = new HashMap();
		InputStream in = HttpClientUtil.String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = HttpsPost.getChildrenText(children);
			}
			
			m.put(k, v);
		}
		
		//关闭流
		in.close();
		
		return m;
	}
    
    /**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	@SuppressWarnings("rawtypes")
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(HttpsPost.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
	
	/**
	 * 获取xml编码字符集
	 * @param strxml
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public static String getXMLEncoding(String strxml) throws JDOMException, IOException {
		InputStream in = HttpClientUtil.String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		in.close();
		return (String)doc.getProperty("encoding");
	}
}
